from django.db.models.fields.files import FileField, FieldFile
from PIL import Image, ImageFont, ImageDraw
import os

def _add_preview(s):
    parts = s.split(".")
    parts[-1] = 'png'
    return ".".join(parts)

class FontFieldFile(FieldFile):
    def _get_thumb_path(self):
        return _add_preview(self.path)
    thumb_path = property(_get_thumb_path)

    def _get_thumb_url(self):
        return _add_preview(self.url)
    thumb_url = property(_get_thumb_url)

    def save(self, name, content, save=True):
        super(FontFieldFile, self).save(name, content, save)

        text = "The quick brown fox jumps over the lazy dog"
        font = ImageFont.truetype(self.path, 18)
        img = Image.new("RGBA", font.getsize(text), (0, 0, 0, 0))
        draw = ImageDraw.Draw(img)
        draw.text((0, 0), text, font=font, fill="black")
        img.save(self.thumb_path, 'PNG')

    def delete(self, save=True):
        if os.path.exists(self.thumb_path):
            os.remove(self.thumb_path)
        super(FontFieldFile, self).delete(save)
                       
class FontField(FileField):
    attr_class = FontFieldFile

    def __init__(self, thumb_width=400, thumb_height=64, *args, **kwargs):
        self.thumb_width = thumb_width
        self.thumb_height = thumb_height
        super(FontField, self).__init__(*args, **kwargs)

